<template>
  <el-dialog
    width="500px"
    title="员工导入"
    :visible="showExcelDialog"
    @close="$emit('update:showExcelDialog', false)"
  >
    <el-row type="flex" justify="center">
      <div class="upload-excel">
        <!-- accept=".xlsx, .xls" 用户可以选择的文件类型 -->
        <input
          ref="excel-upload-input"
          class="excel-upload-input"
          type="file"
          accept=".xlsx, .xls"
          @change="hChange"
        >
        <div class="drop">
          <i class="el-icon-upload" />
          <el-button type="text" @click="download">下载导入模板</el-button>
          <span>将文件拖到此处或
            <el-button type="text" @click="$refs['excel-upload-input'].click()">点击上传</el-button>
          </span>
        </div>
      </div>
    </el-row>
    <el-row type="flex" justify="end">
      <!-- update:props属性名，值 直接修改 .sync修饰符的属性值 -->
      <el-button size="mini" type="primary" @click="$emit('update:showExcelDialog', false)">取消</el-button>
    </el-row>
  </el-dialog>
</template>
<script>
import { getTemplate, importExcel } from '@/api/employee'
import fileSaver from 'file-saver'

export default {
  props: {
    showExcelDialog: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    async download() {
      const res = await getTemplate()
      // console.log(res)
      fileSaver.saveAs(res, '员工信息模板.xlsx')
    },
    async hChange(e) {
      try {
        if (!e.target.files[0]) return
        // 获取 file 对象
        const file = e.target.files[0]
        // console.log(file)
        // 如果直接传普通对象 Content-Type 是 application/json
        // importExcel({ username: 'xxx', file: xxx })
        // 如果传入的是 FormData 对象, Content-Type 会自动设置为 form-data 格式
        const fd = new FormData()
        fd.append('file', file)
        // 将组装好的 FormData 对象传递给服务器
        await importExcel(fd)
        // 提示用户
        this.$message.success('批量导入成功')
        // 关闭弹层
        this.$emit('update:showExcelDialog', false)
        // 重新加载数据
        this.$emit('success')
      } finally {
        // 不管成功还是失败, 都需要清空文件选择框
        // 目的是为了用户选择同一个文件也会继续上传
        this.$refs['excel-upload-input'].value = ''
      }
    }
  }
}
</script>

<style scoped lang="scss">
    .upload-excel {
      display: flex;
      justify-content: center;
      margin: 20px;
      width: 360px;
      height: 180px;
      align-items: center;
      color: #697086;
      .excel-upload-input {
        display: none;
        z-index: -9999;
      }
      .btn-upload,
      .drop {
        border: 1px dashed #dcdfe6;
        width: 100%;
        height: 100%;
        text-align: center;
        line-height: 160px;
        border-radius: 8px;
        display: flex;
        flex-direction: column;
        justify-content: center;
      }
      .drop {
        line-height: 40px;
        color: #bbb;
        i {
          font-size: 60px;
          display: block;
          color: #c0c4cc;
        }
      }
    }
</style>
